package com.study.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.UUID;

public class TaskTest2 {


    //@Scheduled(cron = "0/1 * * * * ?") // 间隔1秒执行
    public void test4() throws Exception{
        //判断线程是否存在
        boolean isAlive = false;
        for (Thread t : Thread.getAllStackTraces().keySet()) {
            if (t.getName().equals("线程1")) {
                isAlive = true;
            }

        }
        if(!isAlive){
            Thread thread1 = new Thread(()->{
                try {
                    Thread.sleep(5000);//休眠5秒
                    System.out.println("子线程已结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"线程1");
            thread1.start();
            System.out.println("线程不存在, 已新建线程并启动");
        }else {
            System.out.println("线程已存在");
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(StrUtil.toStringOrNull(null));
            String aa = "";
            System.out.println(aa.substring(3));
        } catch (Exception e) {
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String str = sw.toString();
            System.out.println("==========");

            System.out.println(str);
            System.out.println("==========");
            System.out.println(Arrays.toString( e.getStackTrace()));
            e.printStackTrace();
            System.out.println("==========");
            System.out.println(getExceptionToString(e));

            String insertSql = "insert into just_error (id, id_card_no, error_msg, error_time, result)"
                    .concat("values(")
                    .concat("'").concat(UUID.randomUUID().toString()).concat("',")
                    .concat("'").concat("idcardNo").concat("',")
                    .concat("'").concat(getExceptionToString(e)).concat("',")
                    .concat("'").concat(DateUtil.now()).concat("',")
                    .concat("'").concat(JSONUtil.toJsonStr("json")).concat("')");
            System.out.println(insertSql);

        }
    }

    /**
     * 获取异常信息
     * @param e
     * @return
     */
    public static String getExceptionToString(Throwable e) {
        if (e == null){
            return "";
        }
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }



}
